<?php
namespace app\controller;

use app\BaseController;
use app\model\Role as RoModel;
use think\facade\Db;
use app\model\RoleNode;
use app\model\Node;
use app\model\Cls as Cs;


class Cls extends BaseController
{
    protected $middleware = [
        // 对所有方法有效
        '\app\middleware\NavCheck',
        '\app\middleware\UrlCheck',
        '\app\middleware\LoginCheck',
    ];
    public function index()
    {
        return view();
    }

   public function data($pid=0)
    {
       $arr = Cs::where('pid',$pid)
           ->field("id,cate_name as title")
           ->select();
       if(!empty($arr)){
               foreach ($arr as $k=>$v){
                   $children =$this->data($v['id']);
                   if (!empty($children)){
                       $arr[$k]['children'] = $children;
                   }
               }
       }

       return $arr;
   }  //无线级分类

   public function add(){

        if($this->request->isPost()){
            $data= $this->request->post();
            $user = new Cs();
            $user->save($data);
            if($user){
                $this->success("添加成功","index");
            }else{
                $this->error("添加失败");
            }
        }
       $pid= $this->request->param('id');

        return view('',['pid'=>$pid]);
   }

   public function del(){
        $id = $this->request->post('id');
        $children = Cs::where('pid',$id)->select()->toArray();
       if(!empty($children)){
            return json(["msg"=>"请先删除掉子商品，再进行删除","code"=>"400"]);
        }

       $user = Cs::find($id);
       if($user->delete()){
          return json(["msg"=>"删除成功","code"=>"0"]);
       }else{
           return json(["msg"=>"删除失败","code"=>"400"]);
       }

   }

   public function update(){
        $post = $this->request->post();
        $user = Cs::find($post['id']);
        if($user['cate_name'] == $post['cate_name']){
            return json(["msg"=>"修改成功","code"=>"0"]);
        }

        $reg = $user->save($post);
        if($reg){
            return json(["msg"=>"修改成功","code"=>"0"]);
        }
            return json(["msg"=>"修改失败","code"=>"400"]);

   }

}
